﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.DAL;
using System.IO;
using System.Transactions;
using System.Data;

namespace MINERP.BLL.CustomerManage
{
    public class MovePhotoBLL
    {
        private DAL.CustomerManage.MovePhotoDAL DCM = new MINERP.DAL.CustomerManage.MovePhotoDAL();

        //属性
        /// <summary>
        /// 照片已移动完毕的订单名称
        /// </summary>
        public string CompletedOrderName { get; set; }
        public int CompletedOrderId { get; set; }

        public string MovePhoto(int userId)
        {
            try
            {
                DataTable dt = DCM.GetMovePhotoCommon(userId);
                NoMovePhoto p = new NoMovePhoto();
                DataRow row=dt.Rows[0];
                p.OldPicPath = row["OldPicPath"].ToString();
                p.OrderId = Convert.ToInt32(row["OrderBagId"]);
                p.OrderName = row["BagName"].ToString();
                p.PhotoId = Convert.ToInt32(row["PhotoId"]);
                p.PicPath = row["PicPath"].ToString();
                if (p.PhotoId == -1)
                {
                    return "10";
                }

                //if (!p.orderInfoReference.IsLoaded)
                //    p.orderInfoReference.Load();
                //if (!p.orderInfo.Tb_OrderBagReference.IsLoaded)
                //{
                //    p.orderInfo.Tb_OrderBagReference.Load();
                //}
                //CompletedOrderId = p.orderInfo.Tb_OrderBag.OrderBagId;
                //CompletedOrderName = p.orderInfo.Tb_OrderBag.BagName;
                CompletedOrderId = p.OrderId;
                CompletedOrderName = p.OrderName;
                //1 移动文件
                int r = Move(p.OldPicPath, p.PicPath);
                if (r == 1)     //源文件与目标文件都不存在
                {
                    return p.OldPicPath+"|"+p.PhotoId.ToString();
                }
                //2 修改状态
                int billResult = ChangeStatus(p);
                if (billResult == -1 || billResult == 0 || billResult == 1)
                {
                    return billResult.ToString();
                }
                return "2";             //成功
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region 移动
        /// <summary>
        /// 移动
        /// </summary>
        /// <param name="src"></param>
        /// <param name="tar"></param>
        /// <returns></returns>
        public int Move(string src, string tar)
        {
            try
            {
                if (!File.Exists(src))
                {
                    if (!File.Exists(tar))
                        return 1;           //源文件与目标文件都不存在
                    else                    //目标文件存在
                    {
                        string fname = src.Substring(src.LastIndexOf("\\") + 1);
                        string backPath = tar.Substring(0, tar.LastIndexOf("\\")) + "\\" + "Backup";
                        if (!Directory.Exists(backPath))
                        {
                            Directory.CreateDirectory(backPath);
                        }
                        string tarBackup = backPath + src.Substring(src.LastIndexOf("\\"));
                        if (!File.Exists(tarBackup))        //目标文件存在，但Backup下没有备份文件
                        {
                            File.Copy(tar, tarBackup, true);
                        }
                    }
                }
                if (File.Exists(src))       //源文件存在
                {
                    if (File.Exists(tar))
                    {
                        File.Delete(tar);
                    }
                    string directory = src.Substring(0, src.LastIndexOf("\\"));
                    File.Move(src, tar);                    //移动
                    //Backup
                    string fname = src.Substring(src.LastIndexOf("\\") + 1);
                    string backPath = tar.Substring(0, tar.LastIndexOf("\\")) + "\\" + "Backup";
                    if (!Directory.Exists(backPath))
                    {
                        Directory.CreateDirectory(backPath);
                    }
                    string tarBackup = backPath + src.Substring(src.LastIndexOf("\\"));
                    File.Copy(tar, tarBackup, true);        //拷贝到Backup
                }
                //删除空目录
                DeleteDirectory(src.Substring(0, src.LastIndexOf("\\")));
                return 2;               //成功
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 当目录中没有文件与子目录时，删除
        /// </summary>
        /// <param name="directory"></param>
        private void DeleteDirectory(string directory)
        {
            try
            {
                if (!Directory.Exists(directory))
                    return;
                string buFen = directory.Substring(directory.LastIndexOf("\\") + 1);
                if (buFen == "已开单")
                    return;
                DirectoryInfo parent = Directory.GetParent(directory);
                string[] files = Directory.GetFiles(directory, "*.jpg");
                string[] directorys = Directory.GetDirectories(directory);
                if (files.Length == 0 && directorys.Length == 0)
                {
                    try
                    {
                        Directory.Delete(directory, true);
                    }
                    catch
                    {
                        DeleteDirectoryExtreme(directory);
                    }
                    DeleteDirectory(parent.FullName);
                }
            }
            catch (Exception ex)
            {
                if (ex is System.IO.IOException)
                {
                    return;
                }
                else
                {
                    throw ex;
                }
            }
        }/// <summary>
        /// 强力删除目录
        /// </summary>
        /// <param name="directory"></param>
        private void DeleteDirectoryExtreme(string directory)
        {
            try
            {
                DirectoryInfo dinfo = new DirectoryInfo(directory);
                dinfo.Attributes = FileAttributes.Normal;
                string[] files = Directory.GetFiles(directory);
                string[] directorys = Directory.GetDirectories(directory);
                if ((files != null && files.Length > 0) || (directorys != null || directorys.Length > 0))
                {
                    foreach (string subFile in files)
                    {
                        File.SetAttributes(subFile, FileAttributes.Normal);
                        File.Delete(subFile);
                    }
                    foreach (string subDirectory in directorys)
                    {
                        DeleteDirectoryExtreme(subDirectory);
                    }
                }
                Directory.Delete(directory);
            }
            catch { }
        }
        #endregion

        #region 修改状态
        /// <summary>
        /// 修改状态
        /// </summary>
        /// <returns></returns>
        public int ChangeStatus(NoMovePhoto photo)
        {
            try
            {
                /*
                System.Transactions.TransactionOptions option = new System.Transactions.TransactionOptions();
                option.Timeout = new TimeSpan(0, 10, 0);
                option.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, option))
                {
                    photo.status = (int)COM.PhotoStatus.NoDistributePrinter;
                    try
                    {
                        DCM.SaveData();
                    }
                    catch (Exception exx1)
                    {
                        DCM.RefreshObject(photo);
                        throw exx1;
                    }
                    orderInfo info = photo.orderInfo;
                    //是否还有照片没有被移动
                        bool isHavePhoto = DCM.IsHavePhotoNoMove(info);
                    int billResult = 100;           //照片移动完毕后，计算订单的预估用钱
                    if (isHavePhoto == false)    //本产品中照片已全部移动
                    {
                        //修改产品状态
                        info.status = (int)COM.OrderInfoStatus.Start;
                        try
                        {
                            DCM.SaveData();
                        }
                        catch (Exception exx2)
                        {
                            DCM.RefreshObject(info);
                            throw exx2;
                        }
                        if (!info.Tb_OrderBagReference.IsLoaded)
                        {
                            info.Tb_OrderBagReference.Load();
                        }
                        Tb_OrderBag order = info.Tb_OrderBag;
                        //订单内的产品是否已全部移动
                        bool isHaveInfo = DCM.IsHaveProductNoMove(order);
                        if (isHaveInfo == false)    //本订单中产品已全部移动
                        {
                            //修改订单状态
                            order.Status = (int)COM.OrderBagStatus.Doing;
                            try
                            {
                                DCM.SaveData();
                            }
                            catch (Exception exx3)
                            {
                                DCM.RefreshObject(order);
                                throw exx3;
                            }
                            //计算预计用钱
                            try
                            {
                                BillBLL bill = new BillBLL();
                                billResult = bill.UpdateBillInfo(order.OrderBagId);
                            }
                            catch (Exception exx)
                            {
                                throw exx;
                            }
                        }
                    }
                    scope.Complete();
                    if (billResult != 100)
                        return billResult;      //-1 orderBagId不存在；0 未照片订单中的某个产品；1 订单中的某个产品还未对订单的商户定价；2 成功
                    return 10;      //10表示当前照片移动成功，继续移动下一张照片
                }
                 */
                int r = DCM.ChangeStatusByStoreProcedure(photo.PhotoId);   //1还有未移动的照片 2还有处于移动状态的产品 3订单状态已修改(改订单下所有照片已移到完毕)
                //if (r == 3)
                //{
                //    BillBLL bill = new BillBLL();
                //    int billResult = bill.UpdateBillInfo(photo.OrderId);
                //    return billResult;          //-1 orderBagId不存在；0 未照片订单中的某个产品；1 订单中的某个产品还未对订单的商户定价；2 成功
                //}
                if (r == 0)
                    throw new Exception("存储过程调用失败！");
                return 10;          //10表示当前照片移动成功，继续移动下一张照片
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取正在移动的订单情况
        /// <summary>
        /// 获取正在移动的订单情况
        /// </summary>
        /// <returns></returns>
        public List<OrderMove> GetOrderMoveInfo()
        {
            try
            {
                List<OrderMove> ListOrderMove = new List<OrderMove>();
                //List<Tb_OrderBag> NoMoveOrders = DCM.GetNoMoveOrders();
                DataTable dt = DCM.GetNoMoveOrders();
                foreach (DataRow order in dt.Rows)
                {
                    OrderMove om = new OrderMove();
                    om.OrderId = Convert.ToInt32(order["OrderBagId"]);
                    om.OrderName = order["BagName"].ToString();
                    om.OrderTime = Convert.ToDateTime(order["OrderTime"]);
                    //List<int> photoNums = DCM.GetPhotoNums(order.OrderBagId);
                    int allPhotoNum = Convert.ToInt32(order["TotalPhotoNum"]);
                    int NoMovePhotoNum = Convert.ToInt32(order["MovePhotoNum"]);
                    int movedPhoto = allPhotoNum - NoMovePhotoNum;
                    om.PhotoNum = movedPhoto.ToString() + "/" + allPhotoNum.ToString();
                    if (allPhotoNum == 0)
                        om.ProcessPosition = 0;
                    else
                        om.ProcessPosition = Convert.ToInt16((double)(movedPhoto) / allPhotoNum * 100);
                    ListOrderMove.Add(om);
                }
                return ListOrderMove;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 将并发状态改回照片等待移动状态
        /// <summary>
        /// 将并发状态改回照片等待移动状态
        /// </summary>
        /// <param name="userId"></param>
        public void ModifyBack(int userId)
        {
            try
            {
                DCM.ModifyBack(userId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        public void ModifyPhotoStatusToPhotoNotExist(int photoId)
        {
            try
            {
                DCM.ModifyPhotoStatusToPhotoNotExist(photoId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region 将等待照片移动的状态改为原始状态
        /// <summary>
        /// 将等待照片移动的状态改为原始状态
        /// </summary>
        public void ModifyPhotoNotExistToPhotoWaitMove()
        {
            try
            {
                DCM.ModifyPhotoNotExistToPhotoWaitMove();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        //数据结构
        public class OrderMove
        {
            public int OrderId { get; set; }
            public string OrderName { get; set; }
            public string PhotoNum { get; set; }
            public int ProcessPosition { get; set; }
            public DateTime OrderTime { get; set; }
        }

        public class NoMovePhoto
        {
            public int PhotoId { get; set; }
            public int OrderId { get; set; }
            public string OrderName { get; set; }
            public string PicPath { get; set; }
            public string OldPicPath { get; set; }
        }
    }
}
